package com.zkw.demo.introspector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * Created by Administrator on 2016/4/6.
 * 通过内省操作javabean
 * 可用BeanUtils工具包代替 http://commons.apache.org/beanutils
 *
 */
public class BeanInfoUtil {
    public static void setProperty(UserInfo userInfo,String userName) throws Exception{
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(userName,userInfo.getClass());
        Method method = propertyDescriptor.getWriteMethod();
        method.invoke(userInfo,"wong");
        System.out.println("set userName:"+userInfo.getUserName());
    }

    public static void getProperty(UserInfo userInfo,String userName) throws Exception{
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(userName,userInfo.getClass());
        Method method = propertyDescriptor.getReadMethod();
        Object objUserName = method.invoke(userInfo);
        System.out.println("get userName:"+objUserName.toString());
    }

    public static void setPropertyByIntrospector(UserInfo userInfo,String userName)throws Exception{
        BeanInfo beanInfo = Introspector.getBeanInfo(userInfo.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if (propertyDescriptors != null && propertyDescriptors.length > 0){
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
                if (propertyDescriptor.getName().equals(userName)){
                    Method method = propertyDescriptor.getWriteMethod();
                    method.invoke(userInfo,"alan");
                    System.out.println("set userName:"+userInfo.getUserName());
                }
            }
        }
    }

    public static void getPropertyByIntrospector(UserInfo userInfo,String userName) throws Exception{
        BeanInfo beanInfo = Introspector.getBeanInfo(userInfo.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        if (propertyDescriptors !=null && propertyDescriptors.length > 0){
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors){
                if (propertyDescriptor.getName().equals(userName)){
                    Method method = propertyDescriptor.getReadMethod();
                    Object objUserName = method.invoke(userInfo);
                    System.out.println("get userName:"+objUserName.toString());
                    break;
                }
            }
        }
    }
}
